﻿using System;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.Text.RegularExpressions;

namespace Portal.CDSP
{
    public class FSearchWP : WebPart
    {

        public override string WebPartId
        {
            get
            {
                return "WebSite.FSearchWP";
            }
        }

        public override string WebPartFolder
        {
            get
            {
                return "Portal.CDSP";
            }
        }
        public override string Title
        {
            get
            {
                return GetText("Title", "CDSP - Tìm kiếm");
            }
        }

        public override ViewCls[] Views
        {
            get
            {
                return new ViewCls[]{
                    new ViewCls("DefaultView",GetText("DefaultView","Tìm kiếm đơn giản"),0),
                               new ViewCls("AdvView",GetText("AdvView","Tìm kiếm nâng cao"),1),
                };
            }
        }

        public override string NameSpace
        {
            get
            {
                return "Portal.CDSP";
            }
        }

        public override string ClassName
        {
            get
            {
                return "FSearchWP";
            }
        }


        [AjaxPro.AjaxMethod]
        public override string ClientRenderWebPart(
            string BelongSite, string TabModuleId,
            string ViewName, string HasPorlet,
            LoadParamCls loadParamCls)
        {
            if (ViewName.Equals("DefaultView"))
            {
                return ClientRenderWebPartDefault(TabModuleId, HasPorlet);
            }

            if (ViewName.Equals("AdvView"))
            {
                return ClientRenderWebPartAdv(TabModuleId, HasPorlet);
            }
            return GetText("ViewNotFound", "Không tìm thấy View [" + ViewName + "]");
        }



        public override DataTable ReadingDataService(string belongSite,
            string ActiveLanguage,
            ref string IdField,
            ref string SubjectField)
        {
            IdField = "Id";
            SubjectField = "Subject";
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("Id");
            dtResult.Columns.Add("Subject");
            dtResult.Rows.Add(new object[]{
                "3E681356-8150-413a-832B-F9B9EA1960BA","Tìm kiếm"
            });
            return dtResult;
        }

        private string ClientRenderWebPartDefault(string TabModuleId, string HasPorlet)
        {
            return RenderForOtherWebPart();
        }

        public string ClientRenderWebPartAdv(string TabModuleId, string HasPorlet)
        {
            try
            {
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));

                string ActiveGroupNewsId = "";
                string ActiveGroupNewsItemId = "";
                string FirstGroupNewsItemId = "0";

                DataTable dtGroupNews = new SearchBLL().ReadingGroupNews();
                string SelectGroupNewsText =
                    "<select id=drpSelectGroupNews onchange=\"javascript:ClientDetectGroupNewsItem();\">\r\n"+
                    "<option value = 0 >---Tất cả---</option>";
                for (int iIndex = 0; iIndex < dtGroupNews.Rows.Count; iIndex++)
                {
                    string GroupNewsId = (string)dtGroupNews.Rows[iIndex]["GroupNewsId"];
                    string GroupNewsName = (string)dtGroupNews.Rows[iIndex][Portal.Environment.Environments.ActiveLanguage + "Subject"];
                    if (GroupNewsId.Equals(ActiveGroupNewsId))
                    {
                        if (FirstGroupNewsItemId.Trim().Length == 0)
                        {
                            FirstGroupNewsItemId = GroupNewsId;
                        }
                        SelectGroupNewsText += "<option selected value=\"" + GroupNewsId + "\">" + GroupNewsName + "</option>\r\n";
                    }
                    else
                    {
                        SelectGroupNewsText += "<option value=\"" + GroupNewsId + "\">" + GroupNewsName + "</option>\r\n";
                    }
                }
                if (FirstGroupNewsItemId.Trim().Length == 0 && dtGroupNews.Rows.Count > 0)
                {
                    FirstGroupNewsItemId = (string)dtGroupNews.Rows[0]["GroupNewsId"];
                }
                SelectGroupNewsText += "</select>\r\n";
                StringBuilder Html = new StringBuilder();

                Html.Append(
                     WebPartUtilities.AttachJavascript(WebPartFolder, "FSearch.js") +
                    "<div id=\"leftsub\">" +
                        "<div class=\"leftsubHeader\">" +
                            "<h3>" + TabModuleCls.Title.ToUpper() + "</h3>" +
                                "<div class=\"clrfix\"></div>" +
                        "</div>" +
                        "<div class=\"leftsubContent\">" +
                            "<div class=\"leftsubContentwrappin\">" +
                            "<div class=\"searchadv\">\n" +
                            "<h4>Tiêu chí tìm kiếm</h4>\n" +
                            "<p>\n" +
                            "<label for=\"keyword\">Từ khóa:</label> <input class=\"keyword\" type=\"text\" name=\"keyword\" id=\"keyword\" />\n" +
                            "</p>\n" +
                            "<p>\n" +
                            "<input type=hidden value=\"" + ActiveGroupNewsItemId + "\" id=\"txtActiveGroupNewsItemId\">" +
                            "<label for=\"drpSelectGroupNews\">" +
                                ResourceBLL.GetText(WebPartId, "GroupNews", "Nhóm") + ":</label>" +
                                SelectGroupNewsText +
                            "</p>\n" +
                            "<p>" +
                               "<label for=\"drpSelectGroupNewsItem\">" +
                                ResourceBLL.GetText(WebPartId, "GroupNewsItem", "Nhóm tin") + ":</label>" +
                                "<div id=\"divGroupNewsItem\">" + BuildGroupNewsItem(FirstGroupNewsItemId, ActiveGroupNewsItemId) + "</div>" +
                            "</p>" +
                            "<p><label for=\"datefrom\">Thời gian từ:</label> " +
                            //"<input class=\"datefrom\" name=\"datefrom\" id=\"datefrom\" /> \n" +
                            Environment.LookUpUtilities.GenerateLookUpDate("datefrom") +
                            "<label class=\"datetolabel\" for=\"dateto\"> đến </label> " +
                            //"<input class=\"dateto\" name=\"dateto\" id=\"dateto\" />\n" +
                            Environment.LookUpUtilities.GenerateLookUpDate("dateto") +
                            "</p>\n" +
                            "<p>\n" +
                            "<a class=\"searchbut\" href=\"#\" onclick  = \"javascript:ClientDoAdvSearch('" + Environments.ActiveLanguage + "','" + TabModuleId + "');\" />Tim kiem</a>\n" +
                            "</p>\n" +
                            "</div>\n" +

                        "<div class=\"clrfix\"></div>" +
                        "</div>" +

                        "<div class=\"leftsubContentwrappin2\">" +
                        "<div id = \"ResultSearchContent\">" +

                        "</div>" +
                        "</div>" +
                        "</div>" +
                    "<div class=\"clear\"></div>" +
                    "</div>");
                return Html.ToString();
            }
            catch (Exception ex)
            {
                return "ERROR:" + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetHtml(string belongSite, string TabModuleId, string Keyword, string ShortGroupNewsItemId, string fromDate, string toDate, int CurrentPage, string JumpJavaScript,string PageSize)
        {
            try
            {
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));

                StringBuilder Html = new StringBuilder();
                Html.Append(
                    Environments.GetExtraStyleSheet(TabModuleCls));               

                    if (Keyword == null) Keyword = "";                                       
                    if (ShortGroupNewsItemId == null) ShortGroupNewsItemId = "";
                    if (Keyword.Trim().Length > 0)
                    {
                        SearchController.AddKeywordToSearched(Keyword.Trim());
                    }
                    string SortType = "DESC";;                    
                    if (SortType.ToLower().Equals("d")) SortType = "DESC";
                    if (SortType.ToLower().Equals("a")) SortType = "ASC";

                    if (fromDate == null) fromDate = "";

                    if (toDate == null) toDate = "";
                    string LimitedItem = "100";

                    if(PageSize == null) PageSize = "25";

                    SimpleSearchParamCls SimpleSearchParamCls = new SimpleSearchParamCls(Keyword);
                    SimpleSearchParamCls.ShortGroupNewsItemId = ShortGroupNewsItemId;
                    SimpleSearchParamCls.SortType = SortType;
                    SimpleSearchParamCls.SortField = "EntryDate";
                    SimpleSearchParamCls.fromDate = fromDate;
                    SimpleSearchParamCls.toDate = toDate;
                    SimpleSearchParamCls.PageSize = int.Parse(PageSize);
                    SimpleSearchParamCls.LimitedItem = int.Parse(LimitedItem);

                    SeeAlsoParamCls[] SeeAlsoParams = new SeeAlsoParamCls[0];                  

                    Html.Append(
                        "<input type=hidden id=txtBelongSite value=\"" + belongSite + "\">" +                        
                        "<input type=hidden id=txtKeyword value=\"" + Keyword + "\">" +
                        "<input type=hidden id=txtFromDate value=\"" + fromDate + "\">" +
                        "<input type=hidden id=txtToDate value=\"" + toDate + "\">" +
                        "<input type=hidden id=txtPageSize value=\"" + PageSize + "\">" +
                        "<input type=hidden id=txtLimitedItem value=\"" + LimitedItem + "\">" +
                        "<input type=hidden id=txtShortGroupNewsItem value=\"" + ShortGroupNewsItemId + "\">" +
                        "<input type=hidden id=txtSortType value=\"" + SortType + "\">");

                    Keyword = Portal.Environment.WebPartUtilities.CorrectForSearch(Keyword);
                    DataTable dataTable = new DataTable();

                    string ActiveLanguage = Environments.ActiveLanguage;
                    StringBuilder Query = new StringBuilder();
                        Query.Append(
                            "select TOP " + LimitedItem.ToString() + " * from TableNews where belongSite='" + belongSite + "' and IsPublishing=1 and ([" + ActiveLanguage + "Body] like N'%" + Keyword + "%' or [" + ActiveLanguage + "Subject] like N'%" + Keyword + "%'  or [SearchKeyword] like N'%" + Keyword + "%')");
                        if (ShortGroupNewsItemId.Trim().Length > 0 && !ShortGroupNewsItemId.Equals("0"))
                    {                        
                        Query.Append(" and left(fk_GroupNewsItem_Id,8)='" + ShortGroupNewsItemId + "'");
                    }
                    if (fromDate.Trim().Length > 0 && toDate.Trim().Length > 0)
                    {
                        string sfd = Portal.Environment.WebPartUtilities.VNDateToDate(fromDate).ToString("MM/dd/yyyy 00:00");
                        string std = Portal.Environment.WebPartUtilities.VNDateToDate(toDate).ToString("MM/dd/yyyy 23:59");
                        Query.Append(" and EntryDate between '" + sfd + "' and '" + std + "'");
                    }

                    string SortField = null;
                    if (SortField == null) SortField = "";
                    if (SortField.Trim().Length > 0)
                    {
                        Query.Append(" order by " + SortField + " " + SortType);
                    }

                    DataTable dtNews = new DataTable();
                    string PublicConnectionString = Environments.PublicConnectionString;
                    SqlDataAdapter da = new SqlDataAdapter(Query.ToString(), new SqlConnection(PublicConnectionString));
                    da.Fill(dtNews);
                    int StartIndex = 0;
                    int EndIndex = 0;
                    string PagingText = new CDSPPaging().GetPaging(TabModuleId, belongSite, dtNews.Rows.Count, 10, 10, CurrentPage, JumpJavaScript, ref StartIndex, ref EndIndex);
                    string SearchKeyword = (string)Environments.Request("sKeyword");
                    while (Keyword.IndexOf("_") >= 0)
                    {
                        Keyword = Keyword.Replace("_", " ");
                    }
                    Html.Append(
                        WebPartUtilities.AttachJavascript(WebPartFolder, "FSearch.js") +
                        
                            "<div class=\"leftsubHeader\">" +
                               "<h4>Kết quả tìm kiếm</h4>" +
                                "<div class=\"clrfix\"></div>" +
                            "</div>" +
                            "<div class=\"textsearch\">" +                        
                                  GetText("SystemHasFound", "Hệ thống tìm thấy") + "&nbsp;<b><i>" + dtNews.Rows.Count.ToString("#,##0") + "</i></b>&nbsp;" +
                                  GetText("ResultMatch", "kết quả phù hợp") +
                            "</div>" +
                            "<div id=divProcessingSearchResult></div>"+
                        "<div class=\"leftsubContent\">");
                    const int MaxValue = 40;
                    for (int iNews = StartIndex; iNews < EndIndex; iNews++)
                    {
                        string ShortContent = "";
                        try
                        {
                            ShortContent = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "ShortContent"];
                        }
                        catch { }
                        string ShortId = (string)dtNews.Rows[iNews]["ShortId"];
                        string Subject = "";
                        try
                        {
                            Subject = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "Subject"];
                        }
                        catch { }
                        string SmallImage = "";
                        try
                        {
                            SmallImage = (string)dtNews.Rows[iNews]["SmallImage"];
                        }
                        catch { }
                        DateTime EntryDate = (DateTime)dtNews.Rows[iNews]["EntryDate"];                        
                        int Count = 0;
                        int j = 0;
                        ShortContent = Regex.Replace(ShortContent, @"<(.|\n)*?>", string.Empty);
                        int Length = ShortContent.Length;
                        for (int i = 1; i < ShortContent.Length; i++)
                        {
                            if (ShortContent[i - 1].ToString().Equals(" ") && !ShortContent[i].ToString().Equals(" "))
                                Count++;
                            if (Count <= MaxValue)
                            {
                                j = i;
                            }
                        }
                        if (Count > MaxValue)
                        {

                            ShortContent = ShortContent.ToString().Remove(j, (Length - j));
                            ShortContent = string.Concat(ShortContent, "...");
                        }
                        string Url = Environments.GetNewsUrl(belongSite, ShortId, Subject, "_runtime");                      
                        Html.Append(
                        "<div class=\"leftsubContentwrappin\">" +
                        "<h3><a href=" + Url + ">" + Subject + "</a>" +
                        "<span class=greynews>(" + EntryDate.ToString("dd/MM/yyyy") + ")</span>" +
                        "</h3>" +
                        "<div class=\"clrfix\"></div>");
                        if (SmallImage.TrimEnd().Length > 0)
                        {
                            string ImageUrl = Environments.HttpMediaRoot + "/media/" + Environments.PortalAlias + "/news/images/" + belongSite + "/" + SmallImage;
                            Html.Append("<a href=\"" + ImageUrl + "\"><img src=\"" + ImageUrl + "\" /></a>");
                        }
                        Html.Append(
                                "<p>" + ShortContent + "</p>" +
                                "<div class=colfix></div>" +
                                "</div>");
                    }

                    if (PagingText.Trim().Length > 0)
                    {
                        Html.Append(PagingText);
                    }
                    Html.Append(                        
                        "</div>");                
                return Html.ToString();
            }
            catch (Exception ex)
            {
                ex.Source = "";
                return Environments.GetClearFix() + GetText("SearchError1", "Lỗi khi tìm kiếm! Xin tìm kiếm lại sau nhé!");// ex.Message.ToString();
            }
        }




        [AjaxPro.AjaxMethod]
        public string BuildGroupNewsItem(string GroupNewsId, string ActiveGroupNewsItemId)
        {
            int LevelIndex = 0;
            DataTable dtTree = new DataTable();
            dtTree.Columns.Add("GroupNewsItemId");
            dtTree.Columns.Add("GroupNewsItemName");

            GetDataForTreeView(ref LevelIndex, ref dtTree, GroupNewsId, null);
            
            string SelectGroupNewsText = "<select id=drpSelectGroupNewsItem>\r\n";

            if (GroupNewsId.Equals("0"))
            {
                SelectGroupNewsText += "<option value = 0 >---Tất cả---</option>";
            }
            else
            {

                for (int iIndex = 0; iIndex < dtTree.Rows.Count; iIndex++)
                {
                    string GroupNewsItemId = (string)dtTree.Rows[iIndex]["GroupNewsItemId"].ToString().Substring(0, 8);
                    string GroupNewsItemName = "(N/A)";
                    try
                    {
                        GroupNewsItemName = (string)dtTree.Rows[iIndex]["GroupNewsItemName"];
                    }
                    catch { }
                    if (ActiveGroupNewsItemId.Equals(GroupNewsItemId))
                    {
                        SelectGroupNewsText += "<option selected value=\"" + GroupNewsItemId + "\">" + GroupNewsItemName + "</option>\r\n";
                    }
                    else
                    {
                        SelectGroupNewsText += "<option value=\"" + GroupNewsItemId + "\">" + GroupNewsItemName + "</option>\r\n";
                    }
                }
            }
            SelectGroupNewsText += "</select>\r\n";
            return SelectGroupNewsText;
        }


        void GetDataForTreeView(ref int LevelIndex, ref DataTable dtTree, string GroupNewsId, string ParentGroupNewsItemId)
        {
            DataTable dtTemp = new SearchBLL().ReadingGroupNewsItems(GroupNewsId, ParentGroupNewsItemId);
            for (int iIndex = 0; iIndex < dtTemp.Rows.Count; iIndex++)
            {
                string GroupNewsItemId = (string)dtTemp.Rows[iIndex]["GroupNewsItemId"];
                string GroupNewsItemName = "(N/A)";
                try
                {
                    GroupNewsItemName = (string)dtTemp.Rows[iIndex][Environments.ActiveLanguage + "GroupNewsItemName"];
                }
                catch { }
                for (int iLevelIndex = 1; iLevelIndex <= LevelIndex; iLevelIndex++)
                {
                    GroupNewsItemName = "-" + GroupNewsItemName;
                }

                dtTree.Rows.Add(new object[]{
                    GroupNewsItemId,GroupNewsItemName
                });
                LevelIndex = LevelIndex + 4;
                GetDataForTreeView(ref LevelIndex, ref dtTree, GroupNewsId, GroupNewsItemId);
                LevelIndex = LevelIndex - 4;
            }
        }


        public string RenderForOtherWebPart()
        {
            try
            {
                string SearchHelp = GetText("SearchGuidle", "tìm kiếm...");
                string SearchKeyword = (string)Environments.Request("sKeyword");
                if (!string.IsNullOrEmpty(SearchKeyword))
                {
                    while (SearchKeyword.IndexOf("_") > 0)
                    {
                        SearchKeyword = SearchKeyword.Replace("_", " ");
                    }
                }
                string Html =
                    WebPartUtilities.AttachJavascript(WebPartFolder, "FSearch.js") +

                    //"<div class=\"AdvSearch\">" +                                        
                    //"</div>"+
                    "<div class=\"quicksearch\">" +
                    
                    "<input name=\"txt_key\" type=\"text\" id=txtSearchKeyword class=\"textsearchbox\" value=\"" + SearchKeyword + "\" onKeyPress=\"return KeyPressForSearch(this,event,'" + Environments.ActiveLanguage + "');\" onfocus=\"if (this.value=='Từ khóa') this.value='' ;\" onblur=\"if (this.value=='') this.value='';\" />" +
                    "<a class=\"searchbut\" href = \"#\" onclick  = \"javascript:ClientDoSimpleSearch('" + Environments.ActiveLanguage + "');\" />" + GetText("SearchButtonTitle", "Tìm kiếm") + "</a>" +
                    "<a class = \"advsearch\" href = \"AdvSearch.aspx\" />" + GetText("AdvSearchTitle", "Tìm kiếm nâng cao") + "</a>" +

                    "</div>";
                return Html;
            }
            catch (Exception ex)
            {
                return "ERROR:" + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod()]
        public string GetResultSearchUrl(string belongSite, string Keyword)
        {
            try
            {
                SearchController.CheckValidKeyword(Keyword);
                Keyword = Keyword.Replace(" ", "_");
                if (System.Web.HttpContext.Current.Session["AppId"] == null)
                {
                    System.Web.HttpContext.Current.Session["AppId"] = System.Guid.NewGuid().ToString();
                }
                return "ResultSearch.aspx?sKeyword=" + Keyword;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            return ResourceBLL.GetText(WebPartId, "Processing", "Đang đọc dữ liệu...");
        }

        public override bool AllowFrontService
        {
            get
            {
                return true;
            }
        }

        public override void RegAjaxPro(System.Web.UI.Page ActivePage)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(FSearchWP), ActivePage);
        }
    }
}

